package com.tudouji.framework.task;

import com.tudouji.common.utils.DateUtils;
import com.tudouji.project.harvest.domain.Procurementcontract;
import com.tudouji.project.harvest.mapper.FreightorderMapper;
import com.tudouji.project.harvest.mapper.ProcurementcontractMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 采收合同自动关闭
 * jsd
 */
@Slf4j
@Component("procurementContractTask")
public class ProcurementContractTask {

    @Autowired
    private ProcurementcontractMapper procurementcontractMapper;
    @Autowired
    private FreightorderMapper freightorderMapper;

    /**
     * 批量关闭采收重量已经达到合同约定重量
     * 、或者超期（采收合同创建时间超过一定期限，比如2个月，且最近比如2周没有发生过业务的）的合同。
     */
    public void prebalance() {
        log.debug("___________________采收合同自动关闭：开始__________________");

        Procurementcontract procurementcontract = new Procurementcontract();
        procurementcontract.setStatus(21);
        List<Procurementcontract> contracts = procurementcontractMapper.selectProcurementcontractList(procurementcontract);

        if (contracts.size() > 0) {
            for (int i = 0; i < contracts.size(); i++) {
                Procurementcontract contract = contracts.get(i);

               BigDecimal weightSum = freightorderMapper.getWeightSumByContract(contract.getGuid());
                weightSum = (weightSum == null ? BigDecimal.ZERO:weightSum);
               long dateDiff = DateUtils.getDateDiff(contract.getCreatedate(), DateUtils.getNowDate());
               int orderSize = freightorderMapper.getFreightOrderByTime(DateUtils.getDateBeforeDay(DateUtils.getNowDate(), -14));
               int compareWeight = weightSum.compareTo(contract.getWeight());
               if (compareWeight == 1 || compareWeight == 0 ||( dateDiff >= 60 && orderSize == 0 )){
                    contract.setStatus(105);
                   procurementcontractMapper.updateProcurementcontract(contract);
               }
            }
        }

        log.info("___________________采收合同自动关闭：结束__________________");
    }

}
